<!DOCTYPE html>

<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <title>RecordTest</title>
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>

<body>
    <button id="btnStart">开始录制</button>
    <button id="btnStop">停止录制</button>
    <br />
    <script>
        if (!navigator.mediaDevices) {
            console.warn(`不支持录制屏幕`);
        }

        var chunks = [];

        var running = true;

        function startAddData() {
            var div = document.createElement('div');
            div.innerHTML = Math.random().toString();
            document.body.appendChild(div);

            if (running) {
                setTimeout(startAddData, 1000);
            }
        }

        navigator.mediaDevices.getDisplayMedia()
            .then(stream => {
                var mediaRecorder = new MediaRecorder(stream);

                document.getElementById('btnStart').onclick = function () {
                    mediaRecorder.start();
                    console.log(mediaRecorder.state);
                    console.log("recorder started");
                    startAddData();
                }

                document.getElementById('btnStop').onclick = function () {
                    mediaRecorder.stop();
                    console.log(mediaRecorder.state);
                    console.log("recorder stopped");
                }

                mediaRecorder.onstop = function (e) {
                    console.log("data available after MediaRecorder.stop() called.");

                    var blob = new Blob(chunks, { 'type': 'video/mp4' });
                    chunks = [];

                    running = false;

                    var videoURL = URL.createObjectURL(blob);

                    window.open(videoURL);

                    console.log("recorder stopped");
                }

                mediaRecorder.ondataavailable = function (e) {
                    chunks.push(e.data);
                }
            })
            .catch(function (err) {
                console.log(err);
            })
    </script>
</body>

</html>